package com.wuxuan.algorithm_homework.string;

import org.junit.jupiter.api.Test;

/**
 * 回文串系列
 *
 */
public class Palindrome {
    /**
     * 判断一个字符串是不是回文串
     *
     * @param s
     * @return
     */
    public boolean isPalindrome(String s) {
        if (s == null || s.length() == 0) {
            return false;
        }
        int left = 0;
        int right = s.length() - 1;
        while (left < right) {
            if ((s.charAt(left)) != s.charAt(right)) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }

    /**
     * 最长回文子串
     * @param s
     * @return
     */
    public String longestPalindrome(String s) {
        if (s == null || s.length() == 0) {
            return s;
        }

        int[] result = new int[2];
        for (int i = 0; i < s.length(); i++) {
            findLongestPanlindrome(s, i - 1, i + 1, result);
            findLongestPanlindrome(s, i, i + 1, result);
        }

        return s.substring(result[0], result[1] + 1);
    }

    private void findLongestPanlindrome(String s, int left, int right, int[] result) {
        while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
            left--;
            right++;
        }
        if ((right - 1) - (left + 1) > result[1] - result[0]) {
            result[1] = right - 1;
            result[0] = left + 1;
        }
    }

    @Test
    public void testFindLongestPanlindrome() {
        String s = "babad";
        String s2 = "aba";
        String s3 = "cbbd";
        System.out.println(longestPalindrome(s));
        System.out.println(longestPalindrome(s2));
        System.out.println(longestPalindrome(s3));
    }
}
